<template>
  <div>
    <el-dialog :visible.sync="value" :before-close="cancel">
      <template slot="title">分单设置</template>
      <el-form :model="form" ref="conditionsSetForm" :rules="conditionsSetRule">
        <el-form-item label="账户名：" prop="accountIds">
        <span class="user-name" v-for="(item,index) in userList" :key="index" v-if="item.check">{{item.title}}
          <i class="user-name__close el-icon-circle-close" @click="delUser(item)"></i>
        </span>
          <i class="el-icon-circle-plus-outline add-user" @click="openUserDidlog"></i>
        </el-form-item>
        <el-form-item label="添加分单方式：">
          <el-radio-group v-model="form.work" size="medium">
            <el-radio :label="1" :value="1">早班</el-radio>
            <el-radio :label="2" :value="2">中班</el-radio>
            <el-radio :label="3" :value="3">晚班</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="条件：">
          <el-checkbox-group v-model="form.conditionIds" @change="handleCheckedCitiesChange">
            <el-checkbox :label="item.id"
                         v-for="item in conditionList"
                         :key="item.id">
              {{item.conditionName}}
            </el-checkbox>
          </el-checkbox-group>
          <div class="el-form-item__error" v-if="conditionIdsError">请选择条件</div>
        </el-form-item>
        <div class="table-head">
          <label >三方出款商户：</label>
          <el-button type="primary" @click="doGet({action: 'getGrid'})">同步三方余额</el-button>
        </div>
        <el-form-item>
          <el-table border :data="tableData"
                    v-loading="loading"
                    element-loading-text="加载中..."
                    @selection-change="handleSelectionChange"
                    class="el-table-align-center">
            <el-table-column type="selection" align="center" width="55"></el-table-column>
            <el-table-column label="三方出款商户" prop="merchantName" align="center"></el-table-column>
            <el-table-column label="商户号" prop="merchantCode" align="center"></el-table-column>
            <el-table-column label="三方账户余额" prop="" align="center">
              <template slot-scope="{row}">
                {{row.amount}}
              </template>
            </el-table-column>
          </el-table>
          <div class="el-form-item__error" v-if="merchantIdsError">请选择三方出款商户</div>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-col :span="16">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="addUserDialog" :before-close="cancel">
      <el-form>
        <el-form-item label="">
          <el-checkbox-group v-model="form.accountIds">
            <el-checkbox :label="item.value"
                         @change="addUser(item)"
                         v-for="item in userList"
                         :key="item.value">
              {{item.title}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUserDialog = false">确 定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { form } from '@/build';
import {
  accountModify, withdrawAccountList, withdrawConditionList, accountBalance,
} from '@/services/api/withdraw';
import { paymentWithdrawOverview } from '@/services/api/payment';

export default {
  name: 'setting-user-dialog',
  mixins: [form],
  props: ['value', 'rowData'],
  data() {
    return {
      form: {
        accountIds: this.rowData.idsArr.map(v => v.value),
        work: 1,
        conditionIds: [],
        remark: this.rowData.remark,
        merchantIds: [],
      },
      merchantIdsError: false,
      conditionIdsError: false,
      ids: [],
      filters: {
        channelId: -1,
      },
      tableData: [],
      userList: [],
      addUserDialog: false,
      conditionsSetRule: {
        accountIds: [
          { type: 'array', required: true, message: '请选择账户名' },
        ],
        conditionIds: [
          { type: 'array', required: true, message: '请选择条件' },
        ],
        remark: [
          { required: true, message: '备注是必填项' },
        ],
      },
      conditionList: [],
    };
  },
  mounted() {

    if (typeof this.rowData.conditionId !== 'object') {
      this.form.conditionIds = this.rowData.conditionId.split(',');
      this.form.conditionIds = _.map(this.form.conditionIds, item => item = Number(item));
    } else {
      this.form.conditionIds = _.map(this.rowData.conditionId, item => item = Number(item));
    }


    this.bindSave(accountModify, 'saveForm', 'form', {
      beforeSend: (data) => {
        _.remove(data.conditionIds, e => e === 0);
        return {
          ...data,
          accountIds: data.accountIds.join(','),
          conditionIds: data.conditionIds.join(','),
          merchantIds: data.merchantIds.join(','),
        };
      },
      afterSuccess: () => {
        this.cancel();
        this.$parent.gridSearch();
      },
    });
    this.bindGet(withdrawAccountList, 'userList', {
      beforeSend: () => ({
        size: 10000,
        page: 1,
        work: -1,
        status: -1,
      }),
      format: data => data.list.map((v, k) => ({
        title: v.userName,
        value: v.id,
        check: this.compareUser(v.id),
      })),
    });
    this.bindGet(paymentWithdrawOverview, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
      format: (data) => {
        const arr = [];
        data.forEach((v, k) => {
          accountBalance({
            merchantId: v.merchantId,
          }).then((data) => {
            this.$set(v, 'amount', data[0] ? (data[1] == -1 ? '不支持三方账户余额查询' : data[1]) : 0);
            arr.push(v);
          });
        });
        return arr;
      },
    });
    this.bindGet(withdrawConditionList, 'conditionList');
    this.getAll();
  },
  methods: {
    handleCheckedCitiesChange(value) {
      if (value.length > 0) {
        this.conditionIdsError = false;
      }
    },
    cancel() {
      this.$emit('input', false);
    },
    handleSelectionChange(val) {
      this.form.merchantIds = val.map(item => item.merchantId);
      if (val.length > 0) {
        this.merchantIdsError = false;
      }
    },
    delUser(item) {
      item.check = false;
      this.$emit('useradd', { value: item.value, check: item.check });
      this.form.accountIds = this.form.accountIds.filter(element => element != item.value);
    },
    addUser(item) {
      item.check = !item.check;
      this.$emit('useradd', { value: item.value, check: item.check });
    },
    compareUser(v) {
      // _.find(this.form.accountIds,v) != undefined
      if (this.form.accountIds.indexOf(v) > -1) {
        return true;
      }
      return false;

    },
    openUserDidlog() {
      this.addUserDialog = true;
    },
    checkCondition() {
      if (this.form.conditionIds.length <= 0) {
        this.conditionIdsError = true;
      } else {
        return new Promise((resolve) => {
          this.form.conditionIds.forEach((v, k) => {
            if (_.find(this.conditionList, { id: v, withdrawType: 2 }) != undefined) {
              if (this.form.merchantIds.length <= 0) {
                this.merchantIdsError = true;
              }
            }
          });
          resolve(this.merchantIdsError);
        });
      }
    },
    submitForm() {
      this.checkCondition().then((data) => {
        if (this.conditionIdsError) {
          return false;
        }
        if (!data) {
          this.doSave({ action: 'saveForm', form: 'conditionsSetForm' });
        } else if (data && this.form.merchantIds.length > 0) {
          this.doSave({ action: 'saveForm', form: 'conditionsSetForm' });
        }
      });

    },
  },
};
</script>

<style lang="scss" scoped>
  .table-head{
    display: flex;
    justify-content: space-between;
  }
  .el-table-align-center{
    margin: 20px 0;
  }
  .user-name{
    display: inline-block;
    min-width: 80px;
    line-height: 25px;
    border: 1px solid #ccc;
    text-align: center;
    border-radius: 30px;
    position: relative;
    margin:0 20px 20px 0;
    .user-name__close{
      display: block;
      width: 20px;
      height: 20px;
      position: absolute;
      top: -8px;
      right: -8px;
      font-size: 18px;
      cursor: pointer;
    }
  }
  .add-user{
    cursor: pointer;
  }
</style>
